Middle of the Linked List
Question
Given a non-empty, singly linked list with head node head, return the middle node of the linked list. If there are two middle nodes, return the second middle node.
Example 1
Input: 1->2->3->4->5
Output: Node 3
Solution
- ▭
- ▯
all//Middle of the Linked List.py
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
all//Middle of the Linked List.py
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow